#include "otherswidget.h"

#include <QPushButton>
#include <QLineEdit>
#include <QLabel>
#include <QTimer>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QGroupBox>

#include "weiqianfunctions.h"
#include <stdio.h>
#include <unistd.h>
#include <QKeySequence>

OthersWidget::OthersWidget(QWidget *parent) : QWidget(parent)
{
     DebugOrRelease=0;
    im = new InputMethod;
    day=0;
    hou=0;
    min=0;
    sec=0;
    year=0;
    QLabel          *pBackLightLabel    = new QLabel;
    QLabel          *pMacLabel          = new QLabel;
    QLabel          *pPingLabel          = new QLabel;
    pruntimeLabel          = new QLabel;
    pusageLabel            = new QLabel;

    QPushButton     *pBackLightBut      = new QPushButton;
    QPushButton     *pBackLightBut1      = new QPushButton;
    QPushButton     *pMacBut            = new QPushButton;
    QPushButton     *pPingBut            = new QPushButton;
    QPushButton     *pclosewifiBut            = new QPushButton;
    QPushButton     *popenwifiBut            = new QPushButton;
    m_pAutoTimer      =new QTimer;
    m_pBackLightEdit    = new QLineEdit;
    m_pMacEdit          = new QLineEdit;
    m_pTimeEdit          = new QLineEdit;
    m_pPingEdit          = new QLineEdit;
    m_pPingEdit1          = new QLineEdit;
    m_pPingErroEdit          = new QLineEdit;
    m_pPingIpEdit        = new QLineEdit;

    m_pMacEdit->installEventFilter(im);
    m_pPingEdit->installEventFilter(im);
    m_pPingEdit1->installEventFilter(im);
 //   m_pPingErroEdit->installEventFilter(im);
    m_pPingIpEdit->installEventFilter(im);
    m_pMacEdit->setObjectName("m_pMacEdit");
    m_pPingEdit->setObjectName("m_pPingEdit");
     m_pPingEdit1->setObjectName("m_pPingEdit1");
   // m_pPingErroEdit->setObjectName("m_pPingErroEdit");
    m_pPingIpEdit->setObjectName("m_pPingIpEdit");
    m_pBackLightEdit->installEventFilter(im);
    m_pBackLightEdit->setObjectName("m_pBackLightEdit");
    connect(im,SIGNAL(setImObjName(QString)),this,SLOT(createImConnect(QString)));//connect the input method

//    QRegExp rx("((2[0-4]//d|25[0-5]|[01]?//d//d?)//.){3}(2[0-4]//d|25[0-5]|[01]?//d//d?)");
//    QRegExpValidator v(rx, 0);
//    qlineedit_ip->setValidator(&v);
//    qlineedit_ip->setInputMask("000.000.000.000;0");

   m_pMacEdit          ->setText(tr("98:13:a3:0f:22:01"));
   m_pPingEdit          ->setText(tr("设置ping次数"));
   m_pPingEdit1          ->setText(tr("设置包大小"));
   m_pPingErroEdit          ->setText(tr("显示丢包率"));
   m_pPingIpEdit             ->setText(tr("192.168.1.1"));
   pusageLabel              ->setText(tr("CPU使用率"));

//  m_pPingErroEdit->setEnabled(false);

system("ifconfig eth0 | grep HWaddr > /tmp/mactmp");

QFile file1("/tmp/mactmp");
file1.open(QFile::ReadOnly);
QString setpath=file1.readAll();
file1.close();
QString mactmp;
int began=0;
for(int i=0;i<setpath.length();i++)
{
 if(setpath[i]=='H' && setpath[i+1]=='W' && setpath[i+2]=='a'){
     began=1;
     i+=6;
 }
 if(began)
     if(setpath[i]!=' ' && setpath[i]!='\n')
     mactmp.append(setpath[i]);

}
   m_pMacEdit          ->setText(mactmp);
//  qDebug()<<m_pMacEdit->text().length();
//  qDebug()<<mactmp;
//  qDebug()<<m_pMacEdit->text();

                    m_pBeepBut          = new QPushButton;
                   // m_pBeepBut->setShortcut(QKeySequence(QLatin1String( "T" )));
                    m_pBeepBut->setShortcut(Qt::Key_Return);

    QGroupBox       *pBackLightGroup    = new QGroupBox;
    QGroupBox       *pMacGroup          = new QGroupBox;
    QGroupBox       *pBeepGroup         = new QGroupBox;

    QHBoxLayout     *pBackLightLayout   = new QHBoxLayout;
    QHBoxLayout     *pBackLightLayout2   = new QHBoxLayout;
    QVBoxLayout     *pBackLightLayout0   = new QVBoxLayout;

  //  QHBoxLayout     *pMacLayout         = new QHBoxLayout;
     QVBoxLayout     *pMacLayout         = new QVBoxLayout;
    QHBoxLayout     *pBeepLayout        = new QHBoxLayout;

     QHBoxLayout     *MacLayout         = new QHBoxLayout;
     QHBoxLayout     *pingLayout         = new QHBoxLayout;

    pBackLightLabel     ->setText(tr("关闭背光时间："));
    pBackLightBut       ->setText(tr("关闭背光"));
    pBackLightBut1       ->setText(tr("满负荷"));
    m_pBackLightEdit    ->setText(tr("5"));
    pMacLabel           ->setText(tr("MAC地址："));
    pPingLabel           ->setText(tr("ping测试："));
    pMacBut             ->setText(tr("设置MAC"));
    pPingBut            ->setText(tr("开始"));
    pclosewifiBut       ->setText(tr("关闭wifi"));
    popenwifiBut       ->setText(tr("打开wifi"));
    m_pBeepBut          ->setText(tr("蜂鸣器测试"));
    m_pBeepBut->setShortcut(Qt::Key_F1);
    pBackLightGroup     ->setTitle(tr("背光测试"));
    pMacGroup           ->setTitle(tr("MAC测试"));
    pBeepGroup          ->setTitle(tr("蜂鸣器测试"));
    pruntimeLabel->setText("0 D 0 Hh 0 M 0 S");
    m_pBackLightEdit->setMaximumSize(100,300);

    pBackLightLabel     ->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pBackLightBut       ->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pBackLightBut1       ->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    m_pBackLightEdit	->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pMacLabel			->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pPingLabel			->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pMacBut             ->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pPingBut             ->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    popenwifiBut           ->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pclosewifiBut           ->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    m_pMacEdit			->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    m_pPingEdit			->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    m_pPingEdit1			->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    m_pPingErroEdit		->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    m_pPingIpEdit       ->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    m_pBeepBut          ->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pBackLightGroup     ->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pMacGroup			->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pBeepGroup			->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    pusageLabel         ->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    m_pPingEdit->setMaximumSize(200,80);
    m_pPingEdit1->setMaximumSize(185,80);
    m_pPingErroEdit->setMaximumSize(180,80);
    m_pPingIpEdit->setMaximumSize(180,80);

    pBackLightLayout    ->addWidget(pBackLightLabel);
     pBackLightLayout    ->addWidget(m_pBackLightEdit);
    if (DebugOrRelease){

    pBackLightLayout    ->addWidget(pusageLabel);
    pBackLightLayout    ->addWidget(pruntimeLabel);
    }

    if (DebugOrRelease)
    pBackLightLayout    ->addWidget(pBackLightBut1);

    pBackLightLayout    ->addWidget(pBackLightBut);
if (DebugOrRelease){
    pBackLightLayout2    ->addWidget(pclosewifiBut);
    pBackLightLayout2    ->addWidget(popenwifiBut);
}
    pBackLightLayout0->addLayout(pBackLightLayout);
    pBackLightLayout0->addLayout(pBackLightLayout2);

            m_pMacEdit->setMinimumSize(700,80);
            MacLayout          ->addWidget(pMacLabel);
            MacLayout          ->addWidget(m_pMacEdit);
            MacLayout          ->addWidget(pMacBut);
            if (DebugOrRelease){
            pingLayout          ->addWidget(pPingLabel);

            pingLayout          ->addWidget(m_pPingEdit);
            pingLayout          ->addWidget(m_pPingEdit1);
            pingLayout          ->addWidget(m_pPingErroEdit);
            pingLayout          ->addWidget(m_pPingIpEdit);
            pingLayout          ->addWidget(pPingBut);
            }


    pMacLayout          ->addLayout(MacLayout);
    pMacLayout          ->addLayout(pingLayout);


    pBeepLayout         ->addWidget(m_pBeepBut);

    pBackLightGroup ->setLayout(pBackLightLayout0);
    pMacGroup       ->setLayout(pMacLayout);
    pBeepGroup      ->setLayout(pBeepLayout);

    QGridLayout *pMainLayout = new QGridLayout;
    pMainLayout->addWidget(pBackLightGroup,     0,0,1,1);
    pMainLayout->addWidget(pMacGroup,           1,0,1,1);
    pMainLayout->addWidget(pBeepGroup,          2,0,1,1);

    this->setLayout(pMainLayout);

    connect(pBackLightBut,      SIGNAL(clicked()),      this,       SLOT(closeBackLight()));
    connect(pBackLightBut1,      SIGNAL(clicked()),      this,       SLOT(closeBackLight1()));
    connect(pMacBut,            SIGNAL(clicked()),      this,       SLOT(setMac()));
    connect(pPingBut,            SIGNAL(clicked()),      this,       SLOT(startPing()));
    connect(pclosewifiBut,            SIGNAL(clicked()),      this,  SLOT(closewifi()));
    connect(popenwifiBut,            SIGNAL(clicked()),      this,  SLOT(openwifi()));
    connect(m_pBeepBut,         SIGNAL(clicked()),      this,       SLOT(setBeep()));
    connect(m_pAutoTimer,      SIGNAL(timeout()),     this,   SLOT(timelian()));
    m_pAutoTimer->start(1000);
/*
    QFile file11("/tmp/time.sh");
    file11.open(QFile::WriteOnly);
    QTextStream s(&file11);
    s<<"#!/bin/sh"<<"\n";
    s<<"cat /proc/uptime | awk -F. '{run_days=$1 / 86400;run_hour=($1 % 86400)/3600;run_minute=($1 % 3600)/60;run_second=$1 % 60;printf(\"runtime:%d day %d hour %d min %d sec \n \",run_days,run_hour,run_minute,run_second)}'> /tmp/liantime.c";
    file11.close();
    system("chmod +x /tmp/time.sh");*/
    timelian1();

}

void OthersWidget::createImConnect(QString ObjName)
{
    disconnect(im->keyboard,SIGNAL(setvalue(QString)),m_pMacEdit,SLOT(setText(QString)));
    disconnect(im->keyboard,SIGNAL(setvalue(QString)),m_pPingEdit,SLOT(setText(QString)));
    disconnect(im->keyboard,SIGNAL(setvalue(QString)),m_pPingEdit1,SLOT(setText(QString)));
 //   disconnect(im->keyboard,SIGNAL(setvalue(QString)),m_pPingErroEdit,SLOT(setText(QString)));
    disconnect(im->keyboard,SIGNAL(setvalue(QString)),m_pBackLightEdit,SLOT(setText(QString)));
    disconnect(im->keyboard,SIGNAL(setvalue(QString)),m_pPingIpEdit,SLOT(setText(QString)));
    if(ObjName=="m_pMacEdit")
        connect(im->keyboard,SIGNAL(setvalue(QString)),m_pMacEdit,SLOT(setText(QString)));
    if(ObjName=="m_pPingEdit")
        connect(im->keyboard,SIGNAL(setvalue(QString)),m_pPingEdit,SLOT(setText(QString)));
    if(ObjName=="m_pPingEdit1")
        connect(im->keyboard,SIGNAL(setvalue(QString)),m_pPingEdit1,SLOT(setText(QString)));
    if(ObjName=="m_pPingIpEdit")
        connect(im->keyboard,SIGNAL(setvalue(QString)),m_pPingIpEdit,SLOT(setText(QString)));
 //   if(ObjName=="m_pPingErroEdit")
   //     connect(im->keyboard,SIGNAL(setvalue(QString)),m_pPingErroEdit,SLOT(setText(QString)));
    if(ObjName=="m_pBackLightEdit")
        connect(im->keyboard,SIGNAL(setvalue(QString)),m_pBackLightEdit,SLOT(setText(QString)));
}
void OthersWidget::cpuUasge()
{
   QString temp;
   int once=1;
   int began=0;
    // system("top -d 10 | grep CPU &> /tmp/alload");
   system("rm /tmp/alload");
    QProcess *proc =new QProcess;
    proc->start("/etc/allad.sh");// fei zu sai
   //  proc->start("top -d 5 | grep CPU > /tmp/alload");
   //   proc->start("top -d 5 /tmp/alload");
  //   sleep(1);
;;;;
     system("killall -9 top");
     QFile file2("/tmp/alload");
     file2.open(QFile::ReadOnly);
     QString setpath1=file2.readAll();
     file2.close();

     for(int i=0;i<setpath1.length();i++) {
         if(setpath1[i]=='C' &&setpath1[i+1]=='P' &&setpath1[i+2]=='U' ){
             began =1;
             i+=5;
         }
         if(began && once && setpath1[i]!='u'){
             temp.append(setpath1[i]);
         }
         if(setpath1[i]=='u' && once)
             once=0;
     }

   //  qDebug()<<temp;
    // qDebug("sdfsf");
     pusageLabel->setText(temp);
}

void OthersWidget::closeBackLight1()
{
	qDebug("closeBackLight1()");
	
    system("killall -9 allload");
    system("./home/asd/allload &");
    system("./home/asd/allload &");
    system("./home/asd/allload &");
    system("./home/asd/allload &");
    ;;;;;;;
   cpuUasge();
}

void OthersWidget::closeBackLight()
{
	 qDebug("closeBackLight()");


    if( (!IsNub(m_pBackLightEdit->text())) ) // bu shi shu zi
         m_pBackLightEdit->setText(tr("5"));

	WeiqianFunctions::SetBackLight(0);
    system("wq_pwm_app.elf /dev/wq_pwm w 1");
    system("wq_pwm_app.elf /dev/wq_pwm w 0");
    QTimer::singleShot(m_pBackLightEdit->text().toInt()*1000, this, SLOT(openBackLight()));
}

void OthersWidget::openBackLight()
{
	qDebug("openBackLight()");

	WeiqianFunctions::SetBackLight(1);
    system("wq_pwm_app.elf /dev/wq_pwm w 128");
}

void OthersWidget::timelian()
{/*
   if(sec<60)
       sec++;
       else if(sec==60){
        sec=0;
        /////////////////////
        if(min<60)
            min++;
              else if(min==60) {
              min=0;
                /////////////////////////////
                if(hou<24)
                    hou++;
                else if(hou==24){
                    hou=0;
                    //////////////////
                    if(day<365)
                        day++;
                    else if(day==365){
                        day=0;
                        year++;
                    }
                    ////////////////////
                }
                //////////////////////////////////////
            }

           //////////////////////////
         }
   QString tmp;
   tmp.append(tr("年"));
   tmp.append(tr("日"));
   tmp.append(tr("时"));
   tmp.append(tr("分"));
   tmp.append(tr("秒"));


   pruntimeLabel->setText(tmp);
*/
    sec++;
    if(600==sec){
        sec=0;
     system( "/etc/time.sh");
     system("cp  /etc/liantime.c  /etc/liantimebk.c");
     system("sync");
      QFile file1("/etc/liantime.c");
      file1.open(QFile::ReadOnly);
      QString setpath=file1.readAll();
      file1.close();
      qDebug()<<setpath;
      pruntimeLabel->setText(setpath);
      cpuUasge();
 }
}
void OthersWidget::timelian1()
{
   // system( "/etc/time.sh");
    QString temp;
     QFile file1("/etc/liantimebk.c");
     file1.open(QFile::ReadOnly);
     QString setpath=file1.readAll();
     file1.close();
  //   qDebug()<<setpath;
     temp="上次运行时间";
     temp.append(setpath);
     pruntimeLabel->setText(temp);
     cpuUasge();
}

void OthersWidget::closewifi()
{
    setBeep();
    system("ifconfig wlan0 down");
}
void OthersWidget::openwifi()
{
     setBeep();
    system("ifconfig wlan0 up");
}

void OthersWidget::clean()
{
    m_pPingErroEdit ->setText("");
}

void OthersWidget::startPing()
{
        //  ping -c 10 192.168.1.16 | grep loss
      setBeep();
      this->clean();
      this->repaint();
   //    QString iptmpall11="sdfsdfsdfsdf";
       QString command ="ping -c ";
       QString command_full = command;
     //  if(m_pPingEdit->is)
    //   m_pPingEdit->setText("5");
       char *S;
       command_full.append(m_pPingEdit->text());
       command_full.append(" -s ");
       command_full.append(m_pPingEdit1->text());
       command_full.append(" ");
       command_full.append(m_pPingIpEdit->text());
       command_full.append(" | grep loss > /tmp/ping.c ");
       qDebug()<<command_full;
       S = (command_full.toAscii()).data();
       system(S);

       QFile file1("/tmp/ping.c");
       file1.open(QFile::ReadOnly);
       QString setpath=file1.readAll();
       file1.close();
       QString iptmp;
       QString iptmpall;
       int beganip=0;
       int stop=0;
     //  qDebug()<<setpath;
       for(int i=0;i<setpath.length();i++)
       {
        if(setpath[i]=='i' && setpath[i+1]=='v' && setpath[i+2]=='e' && setpath[i+3]=='d'&& setpath[i+4]==','){
            beganip=1;
            i+=5;
        }
        if(beganip && setpath[i]!='%')
            if(!stop)
         iptmp.append(setpath[i]);
        if(setpath[i]=='%')
            stop=1;
       }
       qDebug()<<iptmp;
       iptmpall.append(tr("丢包率:"));
       iptmpall.append(iptmp);
       iptmpall.append('%');
       m_pPingErroEdit->setText(iptmpall);

}

void OthersWidget::setMac()
{

    QRegExp rx("[._:_A-Fa-f_0-9_\n_ ]+");
//	QRegExp rx("^([0-9A-F]{2})(-[0-9A-F]{2}){5}$");

     int flag=0;
   
     flag = IsMACaddress(m_pMacEdit->text()) ;  
	 
     if( (m_pMacEdit->text().length()!=17) || (!rx.exactMatch(m_pMacEdit->text())) || (!flag) ) {

		 QDialog * setdialog = new QDialog;
	     QLabel * settmp = new QLabel;

		 settmp->setText(tr("MAC地址格式不对!"));
	     settmp->setStyleSheet("color:red;");

		 QTimer*timer = new QTimer(setdialog);
	     timer->start(800);

		 connect(timer,SIGNAL(timeout()),setdialog,SLOT(close()));

		 QGridLayout *tmplayout = new QGridLayout;
	     tmplayout->addWidget(settmp,0,0,1,1);
	     setdialog->setLayout(tmplayout);
	     setdialog->setWindowFlags(Qt::FramelessWindowHint);
	     setdialog->exec();
	}else if( (m_pMacEdit->text().length()==17)){

	    QByteArray temp = m_pMacEdit->text().toUtf8();
	    const char *pMac = temp.data();

		QFile file1("/usrfs/qtapp/macaddr_sh");

		file1.open(QFile::WriteOnly | QFile::Truncate);//只写形式打开,并清空文件
		QTextStream s(&file1);
		
		s << "#!/bin/sh" << "\n";
		s << "ifconfig eth0 hw ether ";
		s << pMac <<"\n";
		file1.close();

	    usleep(1000);
	    system("sync");
		system("source /usrfs/qtapp/macaddr_sh");

     }
}

void OthersWidget::setBeep()
{
	if(g_lcdsize == LCDSIZE_1024x768)
	{
		QMessageBox::information(NULL, tr("提示"), tr("本产品没有蜂鸣器"));
		return;
	}
    WeiqianFunctions::Beep();
}

OthersWidget::~ OthersWidget()
{

}


